package com.itheima.filter.gatewayfilter;

import com.itheima.common.util.JwtUtil;
import com.itheima.common.util.RequestContext;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

/**
 * @Author：shenkunlin
 * @date： 2021/8/29 15:16
 * @Description：
 ***/
@Component
public class UserServiceGatewayFilterFactory extends AbstractGatewayFilterFactory {

    /**
     * 局部拦截器
     * @param config
     * @return
     */
    @Override
    public GatewayFilter apply(Object config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                //Request、Response
                ServerHttpRequest request = exchange.getRequest();
                ServerHttpResponse response = exchange.getResponse();

                //1)/account/login 登录地址：放行
                String path = request.getURI().getPath();
                if(path.contains("/login")){
                    return chain.filter(exchange);
                }
                //1：获取令牌
                String token = request.getHeaders().getFirst("token");

                //2：解析令牌，判断令牌中的flag是否为1（用户已登录，会员用户信息，0 是游客）
                if(StringUtils.isEmpty(token) || !JwtUtil.verifyToken(token)){
                   //拦截
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
                    return response.writeWith(Flux.just(response.bufferFactory().wrap("身份无效，请您先登录！".getBytes(Charset.forName("UTF-8")))));
                }
                //3：如果flag=0，则拦截请求
                Boolean flag = (Boolean) JwtUtil.parse(token).get("flag");
                if(!flag){
                    //拦截
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
                    return response.writeWith(Flux.just(response.bufferFactory().wrap("游客无权操作，请您先登录！".getBytes(Charset.forName("UTF-8")))));
                }
                return chain.filter(exchange);
            }
        };
    }
}
